<!-- 账户管理 -->
<template>
  <div style="display: flex">
    <div class="content-area">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="手机号">
          <el-input
              v-model="form.mobile"
              disabled
              :placeholder="userData.mobile?mobile:'为了账户安全，请尽快绑定手机号'"
              class="input-with-select"
          >
            <template #append>
              <el-button  @click="BindPhone" type="danger" link>{{ mobileText }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
              v-model="form.email"
              disabled
              :placeholder="userData.email"
              class="input-with-select"
          >
            <template #append>
              <el-button link @click="ChangeAddress">更改</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="账户密码">
          <el-input
              disabled
              placeholder="已设置，可通过账户密码登录"
              class="input-with-select"
          >
            <template #append>
              <el-button link @click="ChangePassword">更改</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="删除账户">
          <div class="updater">
            <div style="margin-left: 10px">删除账户操作不可逆，请谨慎操作！删除账户之前须:</div>
            <div style="display: flex;margin-left: 20px">
              <div style="font-size: 30px">·</div>
              删除&nbsp;&nbsp;<div style="font-weight: bold">我上传的项目</div>
            </div>
            <div style="display: flex;margin-left: 20px">
              <div style="font-size: 30px">·</div>
              删除&nbsp;&nbsp;<div style="font-weight: bold">系统内所有我的信息</div>
            </div>
            <div style="display: flex;margin-left: 20px">
              <div style="font-size: 30px">·</div>
              删除&nbsp;&nbsp;<div style="font-weight: bold">账户将不存在</div>
            </div>
            <div style="margin-left: 10px;font-size: 15px">请在下方输入框中输入手机号以确认操作：</div>
            <el-input type="number" clearable v-model="mobils" placeholder="请输入当前账户手机号"
                      style="width: 290px;margin-left: 20px"></el-input>
            <el-button type="info" @click="Deletes" round style="margin-left: 20px">删除账户
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <el-dialog v-model="dialogTableVisible" width="500">
        <el-card style="max-width: 550px">
          <template #header>
            <div class="card-header">
              <span>身份验证</span>
            </div>
          </template>
          <p style="font-size: 13px">为了你的账户安全，请验证身份。如果手机已注销，请选择邮箱验证。</p>
          <el-select v-model="mobiles" :placeholder="'使用手机'+mobile+'验证'"
                     style="margin-top: 10px;width: 350px">
            <el-option v-if="userData.mobile!=null&&userData.mobile!==''" :label="'使用手机'+mobile+'验证'"
                       value="1"/>
            <el-option v-if="userData.email!=null" :label="'使用邮箱'+userData.email+'验证'" value="2"/>
          </el-select>
          <div style="display: flex;margin-top: 10px">
            <el-input v-model="form.code" placeholder="输入六位验证码" style="width: 220px;"/>
            <el-button class="btn-orange" style="margin-left: 30px" :plain="true" :disabled="disableds"
                       @click="sendCode">{{ valiBtn }}
            </el-button>

          </div>
          <template #footer>
            <el-button round @click="verify" style="margin-left: 180px">验证</el-button>
          </template>
        </el-card>
      </el-dialog>
      <!--        邮箱和手机号-->
      <el-dialog v-model="dialogTable" width="500">
        <div style="font-size: 20px;padding: 10px 10px 10px 10px">{{ change }}</div>
        <hr>
        <br>
        <el-input v-model="form.data" :placeholder="placeh" style="width: 300px;margin-left: 50px;"/>
        <br><br>
        <el-input v-model="form.code" placeholder="输入六位验证码" style="width: 180px;margin-left: 50px;"/>
        <el-button class="btn-orange" style="margin-left: 20px" :plain="true" :disabled="disableds"
                   @click="IsSendCode">{{ valiBtn }}
        </el-button>
        <br><br>
        <hr>
        <br>
        <el-button round @click="AreSure" style="margin-left: 180px">确定</el-button>
      </el-dialog>
      <!--        更改密码-->
      <el-dialog v-model="dialogTables" width="500">
        <div style="font-size: 20px;padding: 10px 10px 10px 10px">{{ change }}</div>
        <hr>
        <br>
        <el-input v-model="form.password" type="password"
                  show-password placeholder="请输入新密码" style="width: 300px;margin-left: 50px;"/>
        <br><br>
        <el-input v-model="form.rePassword" type="password"
                  show-password placeholder="请确认新密码" style="width: 300px;margin-left: 50px;"/>
        <br><br>
        <hr>
        <br>
        <el-button round @click="sumitPassword" style="margin-left: 180px">确定</el-button>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {reactive, ref} from 'vue'
import {useUserStore} from '@/pinia/stores/user'
import {ElMessage, ElNotification} from "element-plus";
const router = useRouter()
import {
  changeEmail,
  changePhone,
  delectUser,
  resetPassword,
  verificationCode
} from "../userData/userApi.js";
import {getLoginCodeApi} from "@/pages/userLogin/index.js";
const disabled = ref(false)
const dialogTableVisible = ref(false)
const dialogTable = ref(false)
const isVerify = ref(false)
const userStore = useUserStore()
let userData = userStore.userInfo
const mobileText = userData.mobile ? "更改" : "绑定"
const mobiles = ref('')
const mobils = ref('')
const mobile = userData.mobile ? userData.mobile.substring(0, 3) + "****" + userData.mobile.substring(7, 11) : ''
const form = reactive({
  mobile: '',
  code: '',
  email: '',
  data: '',
  password: '',
  rePassword: '',
  sex: ''
})
const disableds = ref(false)
const dialogTables = ref(false)
const valiBtn = ref("发送验证码")
const placeh = ref("输入新邮箱")
const change = ref("更改邮箱")
const formImag = reactive({
  file: ''
})
const Deletes = async () => {
  if (mobils.value === "") {
    ElMessage.warning("请输入当前账户的手机号")
  } else if (mobils.value !== userData.mobile) {
    ElMessage.error("手机号码不匹配")
  } else {
    ElMessage.success("删除成功")
    await delectUser(userData.id);
    router.push("/welcome")
  }
}
const time = ref(60)
// 发送验证码
const sendCode = () => {
  time.value = 60
  //验证码倒数60秒
  // 验证电子邮件地址的正则表达式函数
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (userData.email === "" || emailRegex.test(userData.email) === false) {
    ElMessage.error('请输入正确的邮箱');
  } else {
    getLoginCodeApi(userData.email).then(res => {
      if (res.code === 0){
        ElMessage.success("验证码已发送，请注意查收")
      }
    }).catch(error => {
    })
    let timer = setInterval(() => {
      if (time.value === 0) {
        clearInterval(timer);
        valiBtn.value = '获取验证码';
        disableds.value = false;
      } else {
        disableds.value = true;
        valiBtn.value = time.value + '秒后重试';
        time.value--;
      }
    }, 1000);
  }
}
// 验证验证码
const verify =async () => {
  if (form.code === "") {
    ElMessage.error("请输入验证码")
  } else {
    await verificationCode({email: userData.email, code: form.code}).then(res => {
      if (res.code === 0) {
        isVerify.value = true;
        overdue();
        time.value = 0;
        disableds.value = false;
        //保存用户信息
        dialogTableVisible.value = false
        if (change.value === "更改登陆密码") {
          dialogTable.value = false
          dialogTables.value = true
        } else {
          dialogTable.value = true
          dialogTables.value = false
        }
        form.code = ''
        valiBtn.value = "获取验证码"
      } else {
        ElMessage.error("验证码错误")
      }
    }).catch(error => {
    })
  }
}
const overdue = () => {
  setTimeout(() => {
    isVerify.value = false;
  }, 300000)
}
overdue();
const ChangePassword = () => {
  placeh.value = "请输入密码"
  change.value = "更改登陆密码"
  if (isVerify.value) {
    if (change.value === "更改登陆密码") {
      dialogTable.value = false
      dialogTables.value = true
    } else {
      dialogTable.value = true
      dialogTables.value = false
    }
  } else {
    dialogTableVisible.value = true
  }
}
const ChangeAddress = () => {
  placeh.value = "输入新邮箱"
  change.value = "更改邮箱"
  form.data=''
  form.code=''
  if (isVerify.value) {
    if (change.value === "更改登陆密码") {
      dialogTable.value = false
      dialogTables.value = true
    } else {
      dialogTable.value = true
      dialogTables.value = false
    }
  } else {
    dialogTableVisible.value = true
  }
}
const BindPhone = () => {
  placeh.value = "输入11位手机号"
  change.value = "更改手机号"
  form.data=''
  form.code=''
  if (isVerify.value) {
    if (change.value === "更改登陆密码") {
      dialogTable.value = false
      dialogTables.value = true
    } else {
      dialogTable.value = true
      dialogTables.value = false
    }
  } else {
    dialogTableVisible.value = true
  }


}
// 修改密码
const sumitPassword =async () => {
  if (form.password === null) {
    ElMessage.error("请输入密码")
  } else if (form.password.length < 6) {
    ElMessage.error("密码长度不低于六位")
  } else if (form.rePassword === null) {
    ElMessage.error("请确认密码")
  } else if (form.rePassword !== form.password) {
    ElMessage.error("两次输入密码不一致")
  } else {
      await resetPassword({email: userData.email, password: form.password}).then(res => {
      if (res.code === 0) {
        logout();
        // 密码修改成功,3秒后跳转到登陆页面
        setTimeout(() => {
          userStore.logout()
          router.push("/login")
            }, 2000)
        dialogTables.value = false
        valiBtn.value = "发送验证码"
      } else {
        ElMessage.error(res.data.message)
      }
    }).catch(error => {
    })
  }
}
// 增加弹窗
const logout = () => {
  ElNotification({
    title: "提示",
    dangerouslyUseHTMLString: true,
    message: '密码修改成功即将重新登录',
    type: 'info',
    duration: 2100,
  })
}


const IsSendCode = () => {
  if (change.value === "更改手机号") {
    const phone = /^1(3|4|5|6|7|8|9)\d{9}$/;
    if (phone.test(form.data)) {
      sendCode();
    } else {
      ElMessage.error("请输入正确手机号")
    }
  } else {
    const phone = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (phone.test(form.data)) {
      sendCode();
    } else {
      ElMessage.error("请输入正确邮箱")
    }
  }
}
const AreSure =async () => {
  if (change.value === "更改手机号") {
    const phone = /^1(3|4|5|6|7|8|9)\d{9}$/;
    if (form.data === "") {
      ElMessage.error("请输入手机号")
    } else if (phone.test(form.data) === false) {
      ElMessage.error("请输入正确手机号")
    } else if (form.code === "") {
      ElMessage.error("请输入验证码")
    } else if (phone.test(form.data) && form.code !== "") {
      await changePhone({code: form.code, email: userData.email, data: form.data}).then(res => {
        if (res.code === 0) {
          //保存用户信息
          useUserStore().setUserInfo(res.data)
          userData = useUserStore().userInfo
          ElMessage.success("更改成功")
          dialogTable.value = false
          valiBtn.value = "发送验证码"
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(error => {
      })
    }
  } else {
    const phone = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (form.data === "") {
      ElMessage.error("请输入邮箱")
    } else if (phone.test(form.data) === false) {
      ElMessage.error("请输入正确邮箱")
    } else if (form.code === "") {
      ElMessage.error("请输入验证码")
    } else if (phone.test(form.data) && form.code !== "") {
         await changeEmail({code: form.code, email: userData.email, data: form.data}).then(res => {
        if (res.code === 0) {
          //保存用户信息
          useUserStore().setUserInfo(res.data)
          userData = useUserStore().userInfo
          ElMessage.success("更改成功")
          dialogTable.value = false
          valiBtn.value = "发送验证码"
        } else {
          ElMessage.error(res.data.message)
        }
      }).catch(error => {
      })
    }
  }

}

</script>


<style scoped>
.avatar-uploader img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.titles {
  text-align: right;
  width: 100px;
  height: 600px;
  margin-left: 20px;
  background: whitesmoke;
}

.hiddens {
  margin-top: 10px;
  margin-bottom: 10px;
  margin-left: 10px;
}

.updater {
  width: 500px;
  height: 300px;
  border: 1px solid mintcream;
  box-shadow: 0.5px 0.5px 0.5px 1px #888888;
  border-radius: 4px;
}

.content-area {
  width: 800px;
  height: 600px;

}

.upload-demo {
  width: 300px;
  padding: 10px;
}

.el-icon--upload {
  width: 40px;
  height: 40px;
}

.el-upload__text {
  font-size: 15px;
  margin-bottom: 10px;
  margin-top: -10px;
}

.avatar-box-border {
  border: 1px dashed #409eff !important;
}

.avatar-box {
  border-radius: 50%;
  margin-left: 20px;
  cursor: pointer;
  position: relative;
  border: 2px solid #eee;
  overflow: hidden;

  &:hover::before {
    content: '';
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .03);
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .avatar-marker {
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #409eff;

    i.iconfont {
      font-size: 24px;
    }
  }
}
</style>
